package com.qf.springcloud.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

@Component
public class DynamicRouteFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return FilterConstants.SEND_FORWARD_FILTER_ORDER + 500;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Object run() throws ZuulException {
        //1. 获取Request
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();

        //2. 接收serviceId和path参数
        String serviceId = request.getParameter("serviceId");
        String path = request.getParameter("path");

        //3. 如果serviceId和path不为null,去查询Redis中hash结构里的数据
        if(!StringUtils.isEmpty(serviceId) && !StringUtils.isEmpty(path)) {
            String redisServiceId = (String) stringRedisTemplate.opsForHash().get("routes", serviceId);
            String redisPath = (String) stringRedisTemplate.opsForHash().get("routes", path);

            if(!StringUtils.isEmpty(redisServiceId) && !StringUtils.isEmpty(redisPath)) {
                //4. 如果hash结构中的数据不为null,修改路由规则
                requestContext.put(FilterConstants.SERVICE_ID_KEY,redisServiceId);    // 修改路由的服务
                requestContext.put(FilterConstants.REQUEST_URI_KEY,redisPath);        //  修改路由的路径
            }
        }


        return null;
    }
}
